package com.ls.lserp.modules.setting.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.setting.entity.Consumption;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.entity.Process;
import com.ls.lserp.modules.setting.entity.WarehouseShelves;
import com.ls.lserp.modules.setting.service.ConsumptionService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

import freemarker.template.Configuration;
import groovy.util.ResourceException;
import org.springframework.web.servlet.support.RequestContext;

@Controller
@RequestMapping(value = "${adminPath}/fabric/consumption/")
public class ConsumptionController extends BaseController{

    
    @Autowired
    private ConsumptionService consumptionService;
    @Autowired
	Configuration freemarkerConfiguration;
    
    
    /**
     * @Title: get
     * @Description: 获取尺寸尺码信息
     * @param @param id
     * @param @return
     * @return Size 
     * @throws
     */
    @ModelAttribute
   public Consumption get(@RequestParam(required=false) String id) {
       
       // 判断id是否为空
       if (StringUtils.isNotBlank(id)){
           
           // 执行查询语句 查询基本信息
           return consumptionService.get(Long.parseLong(id));
       }else{
           
           // 若为空，实例化
           return new Consumption();
       }
   }
   /**
	 * 进入一览页面
	 * @return
	 */
    @RequiresPermissions("fabric:consumption:view")
    @RequestMapping(value = {""})
    public String list() {
    	
    	// 返回页面地址
        return "modules/setting/consumptionList";
    }
    
    /**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param consumption
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
    @RequiresPermissions("fabric:consumption:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Consumption consumption, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "consumption");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 款式类别
		searchParam.append("&styleCategoryCd=");
		searchParam.append(consumption.getStyleCategoryCd());
		// 版型
		searchParam.append("&fitCd=");
		searchParam.append(consumption.getFitCd());
		// 尺码组
		searchParam.append("&styleSizeGroupCd=");
		searchParam.append(consumption.getStyleSizeGroupCd());
		// 尺码
		searchParam.append("&styleSizeCd=");
		searchParam.append(consumption.getStyleSizeCd());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<Consumption> page = consumptionService.findList(new Page<Consumption>(request, response),consumption);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("consumptions", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
        map.put("springMacroRequestContext", new RequestContext(request));
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("consumption.ftl"), map);
		listMap.put("consumption", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
    
    
    
    @RequiresPermissions("fabric:consumption:view")
    @RequestMapping(value = "form")
    public String form(Consumption consumption,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
    			
    /*	List<Consumption> consuList = consumptionService.findConsumptionList(consumption);
    	consumption.setConsumptionList(consuList);

		// 将查询结果赋值mvc model层返回jsp页面
		 model.addAttribute("consumption", consumption);*/
        if(consumption.getSizeUnitCostId()!=null){

            // 执行查询语句
            consumption = consumptionService.consumptionShow(consumption);

            // 将查询结果赋值mvc model层返回jsp页面
            model.addAttribute("consumption", consumption);

        }
        // 返回页面地址
        return "modules/setting/consumptionEdit";
    }
    
    /**
     * @Title: styleSize
     * @Description: 项目联动
     * @param @param code
     * @param @param model
     * @param @param response
     * @param @return
     * @return String 
     * @throws
     */
    @RequiresPermissions("fabric:consumption:view")
    @RequestMapping(value = "findChild")
    public String findChild(Consumption consumption,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
    			
    	List<Consumption> consumptionChilds = consumptionService.findConsuChildList(consumption.getConsumptionCD());
    	model.addAttribute("consumptionChilds", consumptionChilds);
        // 返回页面地址
        return "modules/setting/consumptionAdd";
    }
    
    
    /**
     * @Title: styleSize
     * @Description: 尺码联动
     * @param @param code
     * @param @param model
     * @param @param response
     * @param @return
     * @return String 
     * @throws
     */
   
   @RequiresPermissions("fabric:consumption:view")
   @RequestMapping(value = "styleSize")
   @ResponseBody
   public String styleSize(String code,Model model,HttpServletResponse response ) {
       
       List<Dict> styleSizeList=DictUtils.getDictList(code);
       
       return renderString(response, styleSizeList);
      
   }
   
   
   /**
    * @Title: show
    * @Description: 查看分类
    * @param @param consumption
    * @param @param model
    * @param @return
    * @return String 
    * @throws
    */
  
  @RequiresPermissions("fabric:consumption:view")
  @RequestMapping(value = "show")
  public String show(Consumption consumption, Model model, HttpServletRequest request, HttpServletResponse response) {
      
      //执行查询语句
      consumption = consumptionService.consumptionShow(consumption);
      // 将查询结果赋值mvc model层返回jsp页面
      model.addAttribute("consumption", consumption);
      
      // 返回页面地址
      return "modules/setting/consumptionShow";
  }
   
   /**
 * @throws ResourceException 
    * @Title: save
    * @Description: 保存数据
    * @param @param Category
    * @param @param request
    * @param @param model
    * @param @param response
    * @param @return
    * @return String 
    * @throws
    */
  
  @RequiresPermissions("fabric:consumption:edit")
  @RequestMapping(value = "save")
  @ResponseBody
  public String save(Consumption consumption, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
	// 判断id是否为null （判断新建或修改）
			if(consumption.getSizeUnitCostId()!= null){
				// 编辑数据
				// 判断数据是否删除
				Consumption consumptionNew = get(consumption.getSizeUnitCostId().toString());
				// 判断数据是否删除
	            if(consumptionNew==null || BaseEntity.DEL_FLAG_DELETE.equals(consumptionNew.getDeleteFlag())){
	            	// 返回提示信息
	            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
	            }
				
	            // 排他处理
			    if(consumption.getVersion()==get(consumption.getSizeUnitCostId().toString()).getVersion()){
			    	
			    	// 版本号加1
			    	consumption.setVersion(consumption.getVersion()+1);
			    }else{
			    	
			    	// 返回提示信息
			    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
			    }
			}else{

                // 新建版本号赋值1
                consumption.setVersion(1L);
            }

      try {

          // 若启用未选择赋值1
          if(consumption.getEnableFlag()==null){
              consumption.setEnableFlag("1");
          }
          if(consumption.getSizeUnitCostId()==null){

              String checkFlag=consumptionService.checkFlag(consumption);
              if(!checkFlag.equals("1")){
                  //新建
                  consumptionService.saveConsumption(consumption);
              }else{
                  return renderString(response,AjaxDone.error(getText("The_consumption_already_exists")));
              }
          }else{
              // 保存分类
              consumptionService.saveConsumption(consumption);
          }
          // 保存成功返回提示信息
          return renderString(response,AjaxDone.ok(getText("size_save_success")));
      } catch (Exception e) {
          // 记录日志
          logger.error(e.getMessage(), e);
          // 提示错误信息
          return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
      }
  }
  
  /**
   * @Title: delete
   * @Description: 删除
   * @param @param Category
   * @param @param response
   * @param @return
   * @return String 
   * @throws
   */
 
 @RequiresPermissions("fabric:consumption:edit")
 @RequestMapping(value = "delete")
 public String delete(Consumption consumption, HttpServletResponse response) {
     
         try {
             // 执行逻辑删除方法
             consumptionService.deleteConsumption(consumption);
         } catch (Exception e) {
             // 记录日志
             logger.error(e.getMessage(), e);
             // 提示错误信息
             return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
         }
         
         // 提示删除成功信息
         return renderString(response,AjaxDone.ok(getText("size_delete_success")));
 }
 
 /**
  * @Title: add
  * @Description: 新建子项
  * @param @param category
  * @param @param redirectAttributes
  * @param @param model
  * @param @return
  * @return String 
  * @throws
  */
@RequiresPermissions("fabric:consumption:edit")
@RequestMapping(value = "add")
public String add(Consumption consumption, Model model) {
	List<Consumption> consumptions = consumptionService.findConsuList();
	model.addAttribute("consumptions", consumptions);
	model.addAttribute("consumption", consumption);
	// 返回页面地址
	return "modules/setting/consumptionAdd";
}
  
   
}
